package util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * This class is a parser which can be used to handle name value pairs in the following form:
 * name:value;name2:value2;name3:value3
 */
public class NameValueParser {

	/**
	 * Just a main method for test.
	 * 
	 * @param args nor arguments required
	 */
	public static void main(String[] args) {
		NameValueParser p = new NameValueParser();
		p.parse("fill:#000011;font-size:Arial;blubb:egal");
		System.out.println(p.setNameValue("peter", "lustig"));
	}
	
	/** The map contains all name value pairs. */
	private Map<String, String> _pairs;
	
	/**
	 * Parses the given string. It must look like the following:
	 * name:value;name2:value2;name3:value3
	 * 
	 * @param string
	 */
	public void parse(String string) {
		_pairs = new HashMap<String, String>();
		String[] tulpel = string.split(";");
		for (int i = 0; i < tulpel.length; i++)
		{
			int split = tulpel[i].indexOf(":");
			String key = tulpel[i].substring(0, split);
			String value = tulpel[i].substring(split + 1);
			_pairs.put(key, value);
		}
	}

	/**
	 * Adds a new name value pair to the list.
	 * If the name already exists, its value will be overwritten.
	 * 
	 * @param name the name
	 * @param value the value
	 * @return returns the complete name value pair list as string
	 */
	public String setNameValue(String name, String value) {
		if (_pairs == null)
		{
			return null;
		}
		_pairs.put(name, value);
		return this.toString();
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("");
		Iterator<Entry<String, String>> iterator = _pairs.entrySet().iterator();
		while (iterator.hasNext())
		{
			Map.Entry<String, String> entry = iterator.next();
			sb.append(entry.getKey() + ":" + entry.getValue() + ";");
		}
		String returnValue = sb.toString();
		return returnValue.substring(0, sb.length() - 1);
	}

}
